# from django.shortcuts import render
# from django.http import JsonResponse
# from rest_framework.parsers import JSONParser
#
# from teacherapp.models import Teacher
# from .models import College,Class,Major
# from rest_framework.decorators import api_view
# # from .models import College
# # Create your views here.
# @api_view(['get'])
# def select(request):
#     id=request.GET.get('id')
#     class_id=request.GET.get('class_id')
#     list= {}
#     listclass={}
#     if id !=None and id !='':
#         list['id']=id
#     if class_id !=None and class_id !='':
#         listclass['class_id']=class_id
#
#     college = College.objects.filter(**list).values()
#     data = []
#     for i in college:
#         classo=Class.objects.filter(major_id=i['id']).values().first()
#         major=Major.objects.filter(college_id=i['id']).values().first()
#         teacher=Teacher.objects.filter(college_id=i['id']).values().first()
#         data.append(i)
#         i['mahor']=major
#         i['class'] = classo
#         i['teacher']=teacher
#     return JsonResponse({"code": "1001", "message": "查询成功","data":data})
# def college(request):
#     colleg = College.objects.filter().values()
#     data=[]
#     for i in colleg:
#         data.append(i)
#     return JsonResponse({"code": "1001", "message": "查询成功", "data": data})
#
from django.core.paginator import Paginator
from django.db.models import Q
from rest_framework.decorators import api_view
from django.http import JsonResponse
from .models import College, Class, Major
from teacherapp.models import Teacher
from rest_framework.parsers import JSONParser

@api_view(['GET'])
def select(request):
    # 获取所有查询参数
    college_id = request.GET.get('college_id')  # 学院ID
    class_id = request.GET.get('class_id')  # 班级号
    grade = request.GET.get('grade')  # 年级
    counselor_name = request.GET.get('counselor_name')  # 辅导员姓名
    page=request.GET.get('page')
    pagesize=request.GET.get('pagesize')

    # 构建查询条件
    filters = Q()
    if college_id:
        filters &= Q(major__college_id=college_id)
    if class_id:
        filters &= Q(class_id=class_id)  # 使用模型中的class_id字段
    if grade:
        filters &= Q(grade=grade)
    if counselor_name:
        filters &= Q(counselor__name__icontains=counselor_name)

    # 查询班级数据（使用select_related优化关联查询）
    classes = Class.objects.filter(filters).select_related('major', 'major__college', 'counselor')
    pageobj=Paginator(classes,pagesize)
    pagebj=pageobj.page(page)
    # 构造响应数据
    data = []
    for cls in pagebj.object_list:
        data.append({
            "class": {
                "class_id": cls.class_id,
                "grade": cls.grade,
                "student_count": cls.student_count,
            },
            "name": cls.major.college.name,  # 学院名称
            "mahor": {  # 专业信息（注意拼写与前端一致）
                "name": cls.major.name
            },
            "teacher": {  # 辅导员信息
                "name": cls.counselor.name if cls.counselor else None
            }
        })

    return JsonResponse({"code": "1001", "message": "查询成功", "data": data,'total':classes.count()})


@api_view(['GET'])
def college(request):
    colleges = College.objects.all().values('id', 'name')
    return JsonResponse({"code": "1001", "message": "查询成功", "data": list(colleges)})
@api_view(['GET'])
def grade(request):
    classp = Class.objects.all().values('grade')
    data=[]
    for i in classp:
        data.append(i)
    return JsonResponse({"code": "1001", "message": "查询成功", "data": data})

@api_view(['POST'])
def add(request):
    data=JSONParser().parse(request)
    Class.objects.filter().create(**data)
    return JsonResponse({"code": "1001", "message": "添加成功"})
@api_view(['DELETE'])
def delete(request,class_id):
    print(class_id)
    classp=Class.objects.filter(class_id=class_id)
    num=classp.count()
    if num ==1:
        classp.delete()
    else:
        return JsonResponse({"code": "1001", "message": "删除失败"})
    return JsonResponse({"code": "1001", "message": "删除成功","class_id":class_id})
@api_view(['PUT'])
def update(request,updateid):
    # updateid = request.GET.get('updateid')
    print(updateid)
    data=JSONParser().parse(request)
    classo=Class.objects.filter(class_id=updateid)
    num=classo.count()
    print(num)
    if num==1:
        classo.update(**data)
        return JsonResponse({"code": "1001", "message": "修改成功"})
    else:
        return JsonResponse({"code": "1001", "message": "修改失败"})
